#include <iostream>
#include <cassert>
#include <vector>
#include <algorithm>
#include <sstream>
#include <list>
using namespace std;


struct ListNode {
    int val;
    ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};
 
class Solution {
public:
    vector<vector<int>> fourSum(vector<int>& nums, int target) {
        vector<vector<int>> rt ;
        int n = nums.size();
        if( n < 4) return rt;
        sort(nums.begin(),nums.end()) ; //升序排列
        //枚举a
        for(int i =0;i< n - 3 ; ++i) {
            if(i>0 && nums[i] == nums[i-1]) continue; //排除重复的
            if(nums[i] + nums[i+1] + nums[i+2] + nums[i+3] > target) break; //找不到满足条件的
            if(nums[i] + nums[n-3] + nums[n-2] + nums[n-1] < target) continue; //当前第一个值太小
            for (int j = i + 1; j < n -2 ;++j) { //枚举第二个数据
                if(j>i+1 && nums[j] == nums[j-1]) continue; //
                if( nums[i] + nums[j] + nums[j+1] + nums[j+2] > target) break; //该条件满足，跳出第二层循环
                if (nums[i] + nums [j] + nums[n - 2] + nums[n-1] < target) continue;

                int left = j + 1, right = n - 1;
                while(left < right) {
                    int sum = nums[i] + nums[j] + nums[left] + nums[right]; //求和
                    if( sum == target) {
                        rt.push_back({nums[i],nums[j] , nums[left],nums[right]}) ;
                        left++;
                        while(left < right && nums[left] == nums[left - 1])++left; //找到了满足条件的，枚举到下一个left的值
                        right--;
                        while(left < right && nums[right] == nums[right + 1])--right; //找到了满足条件的，枚举到下一个left的值
                    } else if  ( sum < target) {
                        left++;
                    } else right--;
                }
            }

        }
        return rt;
    } 
};


int main(){

    vector < vector<int> > ans;
    Solution sp;
    vector<int> nums = {1,0,-1,0,-2,2};
    int target = 0;
    sp.fourSum(nums,target);
    cout<<"hello"<<endl;
    return 0;
}